package main

import (
	"fmt"
	"gowork/goKit/serverKit/service"
	"gowork/goKit/serverKit/util"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	httpTransport "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	"golang.org/x/time/rate"

	kitLog "github.com/go-kit/kit/log"
)

func main() {

	user := service.User{}

	limit := rate.NewLimiter(1,3)

	var logger kitLog.Logger
	{
		logger = kitLog.NewLogfmtLogger(os.Stdout)
		logger = kitLog.WithPrefix(logger, "mykit", "1.0")
		logger = kitLog.WithPrefix(logger, "time", kitLog.DefaultTimestampUTC) //加上前缀时间
		logger = kitLog.WithPrefix(logger, "caller", kitLog.DefaultCaller)     //加上前缀，日志输出时的文件和第几行代码

    }

	endp := service.RateLimit(limit)(service.UserServiceLogMiddleware(logger)(service.GetUserEnpoint(user)))

	//endp := service.GetUserEnpoint(user)

	serverHandle := httpTransport.NewServer(endp, service.DecodeUserRequest, service.EncodecodeUserResponse)

	router := mux.NewRouter()
	//router.Handle(`/user/{uid:\d+}`, serverHandle)

	router.Methods("GET", "DELETE").Path(`/user/{uid:\d+}`).Handler(serverHandle)
	router.Methods("GET").Path("/health").HandlerFunc(func(w http.ResponseWriter, r *http.Request){
		w.Header().Set("Content-type", "application/json")
		w.Write([]byte(`{"status":"ok"}`))
	})

	errChan := make(chan error)

	go (func(){
		util.RegSerrvice()
		err := http.ListenAndServe(":8888", router)
		if err != nil{
			log.Fatal(err)
			errChan <- err
		}
	})()

	go (func(){
		sig_c := make(chan os.Signal)
		signal.Notify(sig_c, syscall.SIGINT, syscall.SIGTERM)
		errChan <- fmt.Errorf("%s", <-sig_c)
	})()
	
	gerErr := <- errChan
	util.UnRegSerrvice()
	log.Println(gerErr)

}